document.addEventListener('DOMContentLoaded', function () {
  const banner = document.querySelector('.banner');
  const track = banner.querySelector('.banner-slides');
  const slides = banner.querySelectorAll('.banner-slide');
  const prevBtn = banner.querySelector('.banner-prev');
  const nextBtn = banner.querySelector('.banner-next');

  // 克隆首尾
  const firstClone = slides[0].cloneNode(true);
  const lastClone = slides[slides.length - 1].cloneNode(true);
  track.appendChild(firstClone);
  track.insertBefore(lastClone, slides[0]);

  let index = 1; // 因为前面多了一个 lastClone
  const slideCount = slides.length + 2; // 加上两个克隆
  const slideWidth = 100; // 假设每张宽度占 100%

  let timer;

  // 初始化位置
  track.style.transform = `translateX(-${index * slideWidth}%)`;

  function goToSlide(i) {
    index = i;
    track.style.transition = 'transform 0.4s ease';
    track.style.transform = `translateX(-${index * slideWidth}%)`;
  }

  function nextSlide() {
    if (index >= slideCount - 1) return;
    goToSlide(index + 1);
  }

  function prevSlide() {
    if (index <= 0) return;
    goToSlide(index - 1);
  }

  // 过渡结束检查是否需要无缝切换
  track.addEventListener('transitionend', () => {
    if (index === slideCount - 1) {
      // 到了克隆的第一张
      track.style.transition = 'none';
      index = 1; // 真实的第一张
      track.style.transform = `translateX(-${index * slideWidth}%)`;
    }
    if (index === 0) {
      // 到了克隆的最后一张
      track.style.transition = 'none';
      index = slideCount - 2; // 真实的最后一张
      track.style.transform = `translateX(-${index * slideWidth}%)`;
    }
  });

  // 自动轮播
  function startAuto() {
    timer = setInterval(nextSlide, 4000);
  }
  function stopAuto() {
    clearInterval(timer);
  }

  // 按钮事件
  prevBtn.addEventListener('click', () => {
    prevSlide();
    stopAuto();
    startAuto();
  });

  nextBtn.addEventListener('click', () => {
    nextSlide();
    stopAuto();
    startAuto();
  });

  // 鼠标悬停暂停
  banner.addEventListener('mouseenter', stopAuto);
  banner.addEventListener('mouseleave', startAuto);

  startAuto();
});
